<template>
  <div class="billing-center">
    <NavBar />
    
    <div class="billing-container">
      <!-- 页面头部 -->
      <div class="page-header">
        <h1>我的账单</h1>
        <p>查看您的账单记录、充值历史和消费明细</p>
      </div>

      <!-- 账单统计 -->
      <div class="billing-stats">
        <div class="stat-card">
          <div class="stat-icon">💰</div>
          <div class="stat-content">
            <div class="stat-number">¥{{ totalRecharge }}</div>
            <div class="stat-label">总充值</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">💳</div>
          <div class="stat-content">
            <div class="stat-number">¥{{ totalConsume }}</div>
            <div class="stat-label">总消费</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">📊</div>
          <div class="stat-content">
            <div class="stat-number">{{ totalRecords }}</div>
            <div class="stat-label">账单数量</div>
          </div>
        </div>
      </div>

      <!-- 筛选和搜索 -->
      <div class="filter-section">
        <el-form inline>
          <el-form-item label="账单类型">
            <el-select v-model="filterType" placeholder="全部类型" style="width: 150px">
              <el-option label="全部类型" value="" />
              <el-option label="充值" value="recharge" />
              <el-option label="消费" value="consumption" />
              <el-option label="退款" value="refund" />
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchRecords">搜索</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 账单列表 -->
      <div class="records-section">
        <div class="section-header">
          <h2>账单记录</h2>
          <el-button type="primary" @click="exportRecords" icon="el-icon-download">
            导出账单
          </el-button>
        </div>

        <div class="records-list">
          <div class="record-item" v-for="record in records" :key="record.id">
            <div class="record-icon">
              <i :class="getRecordIcon(record.bill_type)"></i>
            </div>
            <div class="record-content">
              <div class="record-header">
                <span class="record-type">{{ getBillTypeText(record.bill_type) }}</span>
                <span class="record-subtype" v-if="record.bill_subtype">{{ getBillSubtypeText(record.bill_subtype) }}</span>
                <span class="record-status" :class="getStatusClass(record.status)">
                  {{ getStatusText(record.status) }}
                </span>
              </div>
              <div class="record-details">
                <div class="record-amount">
                  <span class="amount" :class="getAmountClass(record.amount)">
                    {{ record.amount > 0 ? '+' : '' }}¥{{ record.amount }}
                  </span>
                  <span class="balance-info">
                    余额：¥{{ record.balance_after }}
                  </span>
                </div>
                <div class="record-meta">
                  <span class="record-time">{{ formatDateTime(record.created_at) }}</span>
                  <span class="record-method" v-if="record.payment_method">
                    {{ record.payment_method }}
                  </span>
                </div>
              </div>
              <div class="record-description" v-if="record.description">
                {{ record.description }}
              </div>
            </div>
          </div>

          <div class="empty-records" v-if="records.length === 0">
            <i class="el-icon-document"></i>
            <p>暂无账单记录</p>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination-section" v-if="totalRecords > 0">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="totalRecords"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import NavBar from '@/components/NavBarEnhanced.vue'
import { getBillingRecords } from '@/api/membership'
import { getBalanceRecords } from '@/api/balance'
import { ElMessage } from 'element-plus'

export default {
  name: 'BillingCenter',
  components: {
    NavBar
  },
  setup() {
    const route = useRoute()
    const records = ref([])
    const totalRecords = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const filterType = ref('')
    const dateRange = ref([])
    const recordType = ref('billing') // billing or balance

    // 计算统计数据
    const totalRecharge = computed(() => {
      return records.value
        .filter(record => record.bill_type === 'recharge')
        .reduce((sum, record) => sum + parseFloat(record.amount), 0)
        .toFixed(2)
    })

    const totalConsume = computed(() => {
      return records.value
        .filter(record => record.bill_type === 'consumption')
        .reduce((sum, record) => sum + parseFloat(record.amount), 0)
        .toFixed(2)
    })

    // 获取账单记录
    const loadRecords = async () => {
      try {
        const params = {
          page: currentPage.value,
          limit: pageSize.value,
          bill_type: filterType.value
        }

        if (dateRange.value && dateRange.value.length === 2) {
          params.start_date = dateRange.value[0]
          params.end_date = dateRange.value[1]
        }

        let response
        if (recordType.value === 'balance') {
          response = await getBalanceRecords(params)
        } else {
          response = await getBillingRecords(params)
        }
        
        if (response.data.code === 200) {
          records.value = response.data.data.records
          totalRecords.value = response.data.data.total
        }
      } catch (error) {
        console.error('获取记录失败:', error)
        ElMessage.error('获取记录失败')
      }
    }

    // 搜索记录
    const searchRecords = () => {
      currentPage.value = 1
      loadRecords()
    }

    // 重置筛选
    const resetFilter = () => {
      filterType.value = ''
      dateRange.value = []
      searchRecords()
    }

    // 分页处理
    const handleSizeChange = (val) => {
      pageSize.value = val
      loadRecords()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      loadRecords()
    }

    // 获取记录图标
    const getRecordIcon = (billType) => {
      const iconMap = {
        'recharge': 'el-icon-top',
        'consumption': 'el-icon-bottom',
        'refund': 'el-icon-refresh'
      }
      return iconMap[billType] || 'el-icon-info'
    }

    // 获取账单类型文本
    const getBillTypeText = (billType) => {
      const typeMap = {
        'recharge': '充值',
        'consumption': '消费',
        'refund': '退款'
      }
      return typeMap[billType] || billType
    }

    // 获取账单子类型文本
    const getBillSubtypeText = (billSubtype) => {
      const subtypeMap = {
        'membership': '会员费用',
        'balance': '余额相关',
        'service': '服务费用'
      }
      return subtypeMap[billSubtype] || billSubtype
    }

    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        'completed': '已完成',
        'pending': '处理中',
        'failed': '失败',
        'refunded': '已退款'
      }
      return statusMap[status] || status
    }

    // 获取状态样式类
    const getStatusClass = (status) => {
      return `status-${status}`
    }

    // 获取金额样式类
    const getAmountClass = (amount) => {
      return amount > 0 ? 'positive' : 'negative'
    }

    // 格式化日期时间
    const formatDateTime = (dateString) => {
      return new Date(dateString).toLocaleString('zh-CN')
    }

    // 导出账单
    const exportRecords = () => {
      ElMessage.info('账单导出功能开发中，敬请期待')
    }

    onMounted(() => {
      // 检查路由参数，如果是从余额记录跳转过来的
      if (route.query.type === 'balance') {
        recordType.value = 'balance'
      }
      loadRecords()
    })

    // 监听路由参数变化
    watch(() => route.query.type, (newType) => {
      recordType.value = newType === 'balance' ? 'balance' : 'billing'
      loadRecords()
    })

    return {
      records,
      totalRecords,
      currentPage,
      pageSize,
      filterType,
      dateRange,
      recordType,
      totalRecharge,
      totalConsume,
      loadRecords,
      searchRecords,
      resetFilter,
      handleSizeChange,
      handleCurrentChange,
      getRecordIcon,
      getBillTypeText,
      getBillSubtypeText,
      getStatusText,
      getStatusClass,
      getAmountClass,
      formatDateTime,
      exportRecords
    }
  }
}
</script>

<style scoped>
.billing-center {
  min-height: 100vh;
  background: #f5f7fa;
}

.billing-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

.page-header {
  text-align: center;
  margin-bottom: 3rem;
}

.page-header h1 {
  font-size: 2.5rem;
  color: #303133;
  margin-bottom: 0.5rem;
}

.page-header p {
  font-size: 1.1rem;
  color: #606266;
}

/* 账单统计 */
.billing-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 2rem;
  margin-bottom: 3rem;
}

.stat-card {
  background: white;
  border-radius: 1rem;
  padding: 2rem;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.stat-icon {
  font-size: 2.5rem;
  margin-right: 1.5rem;
}

.stat-number {
  font-size: 2rem;
  font-weight: bold;
  color: #303133;
  margin-bottom: 0.25rem;
}

.stat-label {
  color: #909399;
  font-size: 0.875rem;
}

/* 筛选区域 */
.filter-section {
  background: white;
  border-radius: 1rem;
  padding: 2rem;
  margin-bottom: 2rem;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 记录列表 */
.records-section {
  background: white;
  border-radius: 1rem;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 2rem 2rem 1rem;
  border-bottom: 1px solid #f0f0f0;
}

.section-header h2 {
  margin: 0;
  color: #303133;
}

.records-list {
  padding: 1rem 2rem;
}

.record-item {
  display: flex;
  align-items: flex-start;
  padding: 1.5rem 0;
  border-bottom: 1px solid #f0f0f0;
}

.record-item:last-child {
  border-bottom: none;
}

.record-icon {
  width: 3rem;
  height: 3rem;
  background: #f0f9ff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 1.5rem;
  flex-shrink: 0;
}

.record-icon i {
  color: #1890ff;
  font-size: 1.2rem;
}

.record-content {
  flex: 1;
}

.record-header {
  display: flex;
  align-items: center;
  margin-bottom: 0.5rem;
}

.record-type {
  font-weight: 500;
  color: #303133;
  margin-right: 0.5rem;
}

.record-subtype {
  background: #f0f0f0;
  color: #606266;
  padding: 0.25rem 0.5rem;
  border-radius: 0.25rem;
  font-size: 0.75rem;
  margin-right: 0.5rem;
}

.record-status {
  padding: 0.25rem 0.5rem;
  border-radius: 0.25rem;
  font-size: 0.75rem;
  font-weight: 500;
}

.status-completed {
  background: #f0f9ff;
  color: #1890ff;
}

.status-pending {
  background: #fdf6ec;
  color: #e6a23c;
}

.status-failed {
  background: #fef0f0;
  color: #f56c6c;
}

.status-refunded {
  background: #f0f9ff;
  color: #67c23a;
}

.record-details {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.record-amount {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.amount {
  font-size: 1.2rem;
  font-weight: 500;
}

.amount.positive {
  color: #67c23a;
}

.amount.negative {
  color: #f56c6c;
}

.balance-info {
  color: #909399;
  font-size: 0.875rem;
}

.record-meta {
  display: flex;
  align-items: center;
  gap: 1rem;
  color: #909399;
  font-size: 0.875rem;
}

.record-description {
  margin-top: 0.5rem;
  color: #606266;
  font-size: 0.875rem;
}

.empty-records {
  text-align: center;
  padding: 4rem 0;
  color: #c0c4cc;
}

.empty-records i {
  font-size: 4rem;
  margin-bottom: 1rem;
}

/* 分页 */
.pagination-section {
  padding: 2rem;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .billing-container {
    padding: 1rem;
  }
  
  .record-details {
    flex-direction: column;
    align-items: flex-start;
    gap: 1rem;
  }
  
  .record-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
  }
  
  .section-header {
    flex-direction: column;
    gap: 1rem;
  }
}
</style>